package com.heima.search.service.impl;

import com.heima.es.service.EsService;
import com.heima.model.common.constants.search.SearchConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.threadlocal.AppThreadLocalUtils;
import com.heima.model.search.dtos.UserSearchDTO;
import com.heima.model.search.vos.SearchArticleVO;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.service.ApUserSearchService;
import com.heima.search.service.ArticleSearchService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.bouncycastle.eac.operator.EACSignatureVerifier;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ArticleSearchServiceImpl implements ArticleSearchService {
    @Autowired
    EsService<SearchArticleVO> esService;

    @Value("${file.minio.readPath}")
    String readPath;
    @Value("${file.oss.web-site}")

    String webSite;
@Autowired
    ApUserSearchService apUserSearchService;
    @Override
    public ResponseResult search(UserSearchDTO userSearchDto) {
        //参数校验
        String searchWords = userSearchDto.getSearchWords();
        if (userSearchDto == null || StringUtils.isBlank(searchWords)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        ApUser user = AppThreadLocalUtils.getUser();

        userSearchDto.setUserId(user==null?null:user.getId());
        apUserSearchService.insert(userSearchDto);

        Date minBehotTime = userSearchDto.getMinBehotTime();
        if (minBehotTime==null){
            userSearchDto.setMinBehotTime(new Date());
        }

        if (userSearchDto.getPageSize()<=0){
            userSearchDto.setPageSize(10);
        }
        //1.构建搜索条件
        SearchSourceBuilder builder = new SearchSourceBuilder();
        //1.1 创建bool条件
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //1.2 将  分词查询关键字 加入到bool条件 must
        boolQuery.must( QueryBuilders.matchQuery("title",userSearchDto.getSearchWords()));
       boolQuery.filter(QueryBuilders.rangeQuery("publishTime").lt(userSearchDto.getMinBehotTime()));
       builder.query(boolQuery);

        //1.3将 查询发布时间小于最小时间 加入bool条件  filter
        //1.4设置分页 size
        builder.size(userSearchDto.getPageSize() );
        //1.5按照发布时间降序排序
        builder.sort("publishTime", SortOrder.DESC);
        //1.6 设置文章标题高亮处理
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");
        highlightBuilder.preTags("<font style='color: red; font-size: inherit;'>");
        highlightBuilder.postTags("</font>");
        builder.highlighter(highlightBuilder);


        //2.执行搜索
        PageResponseResult search = esService.search(builder, SearchArticleVO.class, SearchConstants.ARTICLE_INDEX_NAME);
        List<SearchArticleVO> list = (List<SearchArticleVO>)search.getData();
        for (SearchArticleVO searchArticleVO : list) {
            String images = searchArticleVO.getImages();
            if (StringUtils.isNotBlank(images)){
                images=  Arrays.stream(images.split(","))
                        .map(url -> webSite+url)
                        .collect(Collectors.joining(","));
                searchArticleVO.setImages(images);
            }

            searchArticleVO.setStaticUrl(readPath+searchArticleVO.getStaticUrl());
        }
        //3.封装响应结果
        search.setData(list);
        return search;
    }


    @Override
    public void saveArticle(SearchArticleVO article) {
      //  esService.save(article,APP_INFO_ARTICLE);
    }
    @Override
    public void deleteArticle(String articleId) {
      //  esService.deleteById(APP_INFO_ARTICLE,articleId);
    }
}
